use chrono::Local;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};

pub const TARGET_DIR_NAME: &str = "1rs"; // 目标目录名称
pub const ANDROID_STORAGE_ROOT: &str = "/storage/emulated/0"; // Android 存储根目录
pub const ANDROID_EXECUTABLE_DIR: &str = "/data/local/tmp"; // Android 可执行文件目录
pub const DOWNLOAD_DIR_NAME: &str = "Download"; // 下载目录名称

pub fn get_executable_dir() -> PathBuf {
    if cfg!(target_os = "android") {
        PathBuf::from(ANDROID_EXECUTABLE_DIR)
    } else {
        dirs::home_dir().unwrap()
    }
}

pub fn get_download_path() -> PathBuf {
    println!("target os: {}", std::env::consts::OS);
    #[cfg(any())] // android only
    if cfg!(target_os = "android") {
        PathBuf::from(ANDROID_STORAGE_ROOT).join(DOWNLOAD_DIR_NAME)
    } else {
        dirs::home_dir().unwrap().join(DOWNLOAD_DIR_NAME)
    }
    PathBuf::from(ANDROID_STORAGE_ROOT).join(DOWNLOAD_DIR_NAME)
}

// 新的目标目录
pub fn get_target_dir() -> PathBuf {
    println!("target os: {}", std::env::consts::OS);
    #[cfg(any())] // android only
    if cfg!(target_os = "android") {
        PathBuf::from(ANDROID_STORAGE_ROOT).join(TARGET_DIR_NAME)
    } else {
        dirs::home_dir().unwrap().join(TARGET_DIR_NAME)
    }
    PathBuf::from(ANDROID_STORAGE_ROOT).join(TARGET_DIR_NAME)
}

pub fn setup_work_dir(prefix: &str) -> std::io::Result<(PathBuf, PathBuf, PathBuf)> {
    let down_dir = get_download_path();
    println!("Processing files in directory: {}", down_dir.display());

    let timestamp = Local::now().format("%y%m%d-%H%M");
    let tmp_dir_name = format!("{}{}", prefix, timestamp);

    // 在目标目录下创建新目录
    // 创建工作目录
    let target_dir = get_target_dir();
    let dest_dir = target_dir.join(&tmp_dir_name);
    let down_tmp_dir = down_dir.join(&tmp_dir_name);

    // 创建所需的目录
    for dir in [&dest_dir, &down_tmp_dir] {
        println!("Creating directory: {}", dir.display());
        if let Err(e) = fs::create_dir_all(dir) {
            eprintln!("can't create directory {}: {}", dir.display(), e);
            eprintln!("please check if directory exists and has write permission");
            return Err(e);
        }
    }

    Ok((down_dir, dest_dir, down_tmp_dir))
}

pub fn move_to_target_dir(src_dir: &Path, dest_dir: &Path) -> std::io::Result<()> {
    println!("Moving directory to: {}", dest_dir.display());
    fs::rename(src_dir, &dest_dir)?;
    Ok(())
}
